<?php

namespace App\Http\Controllers\Home;

use App\Models\BalanceLogs;
use App\Models\Configs;
use App\Models\Mails;
use App\Models\SmsLogs;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Models\Phonemap;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Mews\Captcha\Facades\Captcha;

class MyphoneController extends Controller
{
    protected $accountSid;
    protected $appid;
    protected $key;
    protected $type;
    protected $op;
    protected $baseurl;
    protected $smsbaseurl;

    function __construct()
    {
        $this->accountSid = '8a216da86bfdbebb016c83d1f2c801bb';
        $this->appid = '8a216da86bfdbebb016c83d1f2e701bc';
        $this->key = '2d778297afd5406eb533fa3be55cdaf0';
        $this->type = 'axb';
        $this->op = '';
        $this->baseurl = 'https://apppro.cloopen.com:8883/2013-12-26';
        $this->smsbaseurl = 'https://app.cloopen.com:8883/2013-12-26';
    }

    /**
     * 虚拟电话
     * @route home.phone.phoneMap
     * @param phoneA HR电话
     * @param store_id 供应商id
     */
    public function phoneMap(Request $request)
    {
        //19-9-19 by z 限制用户拨打电话 start
        $uId = auth()->guard('web')->id();//当前登录用户id
        if(empty($uId)){
            if (empty($uId)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
        }
        $users = Users::getUserInfo(['id'=>$uId],['status']);
        if($users['status'] != 1){
            if($users['status'] == 2){
                $message = '账号未审核，请联系后台管理员审核！';
            }elseif($users['status'] == 3){
                $message = '账号未审核通过，请联系查看原因并重新提交审核！';
            }elseif ($users['status'] == 4){
                $message = '你的账号已锁定，请联系客服!';
            }else{
                $message = '系统错误，请联系后台管理员！';
            }
            return $this->writeJson(1,null , $message);
        }
        //end

        $phoneA = $request->post('phoneA');//当前登录hr用户的电话
        $store_id = $request->post('store_id');
        if (empty($phoneA)||empty($store_id)) return response()->json(["code"=>1, "msg"=>'参数错误']);
        $user_id = Stores::where('id',$store_id)->value('user_id');//供应商所属用户id
//        //判断余额是否足够
//        $user_info = Users::where('id',$user_id)->first(['username','balance']);
//        $base = Configs::getConfig('base');
//        if ($user_info['balance'] < $base['call_balance']){
//            $msg = '申请电话隐私保护失败，供应商['.$user_info['username'].']余额不足，请联系客服电话 :'.$base['customer_mobile'];
//            return $this->writeJson(1,null , $msg);
//        }
        //返回前端需要的信息
        $phone_info = [];
        $phone_info['master_name'] = UserInfos::where('user_id',$user_id)->value('master_name');//供应商负责人姓名
        $phoneB = Users::where('id',$user_id)->value('mobile');//供应商负责人电话
        //供应商无联系方式接通到平台电话
        if(empty($phoneB)){
            $phoneB = $base['customer_mobile'];
        }

        $client = new Client();
        $mothed = 'POST';
        $mapTime = 60 * 10;
        $timestamp = time();
        //是否有最近做过这两个号码到映射
        $map_info = Phonemap::where('anumber',$phoneA)->where('bnumber',$phoneB)->where('status',1)->first();
        if($map_info['timestamp']>$timestamp){
            $phone_info['master_phone'] = $map_info['xnumber'];
            return $this->writeJson(0,$phone_info , '申请电话隐私保护成功!');
        }
        $auth = "$this->accountSid:" . date("YmdHis", $timestamp);
        $auth = base64_encode($auth);
        $sigParameter = $this->accountSid . $this->key . date("YmdHis", $timestamp);
        $sigParameter = md5($sigParameter);
        $baseUrl = $this->baseurl . "/Accounts/$this->accountSid/nme/$this->type/cu01/providenumber?sig=$sigParameter";
        $data = [
            'appId' => $this->appid,
            'aNumber' => $phoneA,
            'bNumber' => $phoneB,
            'xNumberRestrict' => '0',
            'mappingDuration' => $mapTime,
            'needRecord' => '1',
            'userData'=> $timestamp.'_'.$phoneA,
            'cdrNotifyUrl' => route('home.phone.phonecallback'),
        ];

        $info = [
            'log_id' => $timestamp.'_'.$phoneA,
            'anumber' => $phoneA,
            'bnumber' => $phoneB,
            'xnumber' => '',
            'timestamp' => $timestamp+$mapTime,
            'response' => '',
            'status' => 1,
        ];
        $response = $client->request($mothed, $baseUrl, [
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json;charset=utf-8',
                'Authorization' => $auth,
            ],
            'json' => $data,
        ]);

        $ret = $response->getBody()->getContents();
        $info['response'] = $ret;
        $ret = json_decode($ret, true);

        $statusCode = 0;
        $msg = '申请电话隐私保护成功!';
        $rdata = '';
        if ($ret['statusCode'] != '000000') {//成功
            $info['status'] = 0;
            $statusCode = 1;
            $msg = '申请电话隐私保护失败，请联系后台管理员!';
        }else{
            $rdata=$ret['data']['xNumber'];
            $info['xnumber'] = $rdata;
        }
        $phone_info['master_phone'] = $rdata;

        Phonemap::create($info);

        return $this->writeJson($statusCode, $phone_info, $msg);

    }

    /**
     * 虚拟电话 话单回调
     */
    public function phoneCallback(Request $request){
//        Log::info('电话回调：',json_decode(json_encode($request), true));
        $ret = $request->all(['callId','userData','answerTime','calleeRingTime','callerNum','calleeNum','callerDuratin','duration','startTime','endTime']);

        file_put_contents('phonemap.log',json_encode($ret));
        $log_info = Phonemap::where('log_id',$ret['userData'])->first();
        file_put_contents('phonemap.log',json_encode($log_info),FILE_APPEND);
        if($log_info['connet_status']>0){
            return ["statusCode"=>"000000"];
        }
        file_put_contents('phonemap.log',json_encode(floor((strtotime($ret['endTime'])-strtotime($ret['calleeRingTime']))%86400%60)),FILE_APPEND);

        if($ret['answerTime']>""){
            $ret['endTime']=$ret['answerTime'];
        }
        if($ret['duration']<15&&$ret['duration']>0){
            $log_info['connet_status'] = 3;//已沟通，未扣费
            Phonemap::where('log_id',$log_info['log_id'])->update($log_info->toArray());
        }
        if($ret['duration']>15||(floor((strtotime($ret['endTime'])-strtotime($ret['calleeRingTime']))%86400%60)>30)){
            $log_info['connet_status'] = 1;
            if($ret['duration']>15){
                $log_info['connet_status'] = 2;
            }
            Phonemap::where('log_id',$log_info['log_id'])->update($log_info->toArray());
            file_put_contents('phonemap.log',json_encode($ret['calleeRingTime']),FILE_APPEND);
            //通话时间大于15s，发送短信
            $param = [];
            $gys = Users::getUserInfo(['mobile'=>$ret['calleeNum']]);
            $param[]=$gys['username'];
            $param[]=$ret['calleeNum'];
            $this->sendSMS($ret['callerNum'],474571,$param);

            $param = [];
            $param[]=$ret['callerNum'];
            $this->sendSMS($ret['calleeNum'],474574,$param);

            //扣除供应商信息费，并发送扣费站内信
            $base = Configs::getConfig('base');
            Users::where('id',$gys['id'])->decrement('balance',$base['call_balance']);//扣除余额
            Stores::where('user_id',$gys['id'])->increment('call',1);//致电量+1
            //余额日志记录
            $balance = [
                'user_id' => $gys['id'],
                'user_name' => $gys['username'],
                'balance' => '-'.$base['call_balance'],
                'desc' => 'hr拨打电话扣除余额',
                'type' => 2,
            ];
            BalanceLogs::create($balance);
            //发送站内信-hr拨打电话扣除余额
            $mails = [
                'title' => 'hr拨打电话扣除余额',
                'content' => 'hr拨打了您的电话',
                'user_id' => $gys['id'],
                'status' => 1,
                'type' => 1,
            ];
            Mails::create($mails);
        }
        return ["statusCode"=>"000000"];
    }

    /**
     * 获取短信验证码
     * @route home.phone.getSMS
     * @param captcha 图形验证码
     * @param phone 电话号码
     */
    public function getSMS(Request $request){
        //验证图片验证码
        $captcha = $request->post('captcha');
        $data = [ 'captcha' => $captcha];
        $rules = [ 'captcha'  => 'required|captcha' ];
        $msgs = [
            'captcha.required'  => '请填写图形验证码',
            'captcha.captcha'   => '图形验证码错误',
        ];
        $validator = validator()->make($data,$rules,$msgs);
        if ($validator->fails()) {
            return $this->writeJson(1,null,$validator->errors()->first());
        }

        $phone = $request->post('phone');
        if (empty($phone)) return $this->writeJson(1,null,'请输入电话号码');

        $cache = cache()->get('sms-'.$phone);
        //20秒的频繁验证
        if($cache && Carbon::now()->timestamp - $cache['time'] < 20){
            if (empty($phone)) return $this->writeJson(1,null,'您的操作太频繁!');
        }

        $code = '123456';//生成验证码
//        $code = rand(100000,999999);//生成验证码
        $param = [];
        $param[]=$code;
        $param[]='2分钟';
        $ret = $this->sendSMS($phone,474566,$param);
        if($ret == '000000'){
            //保存验证码到缓存用于验证
            $time = Carbon::now()->timestamp;
            //2分钟的过期时间
            cache()->add('sms-'.$phone, ['code'=>$code, 'time'=>$time],120);
            return $this->writeJson(0,null,'发送成功');
        }elseif ($ret == '160040'){
            return $this->writeJson(1,null,'该号码超出当天发送上限');
        }elseif ($ret == '160034'){
            return $this->writeJson(1,null,'高危投诉号码黑名单');
        }elseif ($ret == '160038'){
            return $this->writeJson(1,null,'该号码发送太过频繁');
        }else{
            return $this->writeJson(1,null,'发送失败');
        }
    }

    /**
     * 发送短信验证码
     * @route home.phone.sendSMS
     */
    public function sendSMS($phone, $templateId=1, $param=''){
        if (empty($phone)||empty($templateId)) return $this->writeJson(1,null,'参数错误');

        $client = new Client();
        $mothed = 'POST';
        $timestamp = time();
        //【云通讯】您使用的是云通讯短信模板，您的验证码是{1}，请于{2}分钟内正确输入。
        $auth = "$this->accountSid:" . date("YmdHis", $timestamp);
        $auth = base64_encode($auth);
        $sigParameter = $this->accountSid . $this->key . date("YmdHis", $timestamp);
        $sigParameter = md5($sigParameter);
        $baseUrl = $this->smsbaseurl . "/Accounts/$this->accountSid/SMS/TemplateSMS?sig=$sigParameter";
        $data = [
            'appId' => $this->appid,
            'to' => $phone,
            'templateId' => $templateId,
            'datas' => $param,
        ];
        $info = [
            'phone' => $phone,
            'tid' => $templateId,
            'response' => '',
            'status' => 1,
        ];
        $response = $client->request($mothed, $baseUrl, [
            'headers' => [
                'Accept' => 'application/json',
                'Content-Length'=> 256,
                'Content-Type' => 'application/json;charset=utf-8',
                'Authorization' => $auth,
            ],
            'json' => $data,
        ]);
        $ret = $response->getBody()->getContents();
        $info['response'] = $ret;
        $ret = json_decode($ret, true);

//        $statusCode = 1;
        if ($ret['statusCode'] != '000000') {//失败
            $info['status'] = 0;
//            $statusCode = 0;

        }
        SmsLogs::create($info);
//        return $statusCode;
        return $ret['statusCode'];
    }
}